package com.siyoumi.app.modules.mall2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.M2Sku;
import com.siyoumi.app.entity.M2Spu;
import com.siyoumi.app.entity.SysStock;
import com.siyoumi.app.modules.mall2.service.SvcM2Sku;
import com.siyoumi.app.modules.mall2.service.SvcM2Spu;
import com.siyoumi.app.modules.mall2.vo.SkuData;
import com.siyoumi.app.modules.mall2.vo.SkuSetStockVo;
import com.siyoumi.app.service.SysStockService;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.exception.XException;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SvcM2SkuImpl
        implements SvcM2Sku {
    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<M2Sku> listQuery(String spuId, List<String> skuids) {
        JoinWrapperPlus<M2Sku> query = SvcM2Sku.getApp().join();
        query.eq("msku_x_id", XHttpContext.getX())
                .eq("msku_del", 0);
        if (skuids != null) { //sku
            query.in("msku_id", skuids);
        }
        if (XStr.hasAnyText(spuId)) { //商品id
            query.eq("msku_spu_id", spuId);
        }

        return query;
    }


    /**
     * 根据属性ID获取sku
     *
     * @param attrSkuId0
     * @param attrSkuId1
     * @param attrSkuId2
     */
    public M2Sku getEntitySku(String attrSkuId0, String attrSkuId1, String attrSkuId2) {
        QueryWrapper<M2Sku> query = SvcM2Sku.getApp().q();
        query.eq("msku_del", 0);
        if (XStr.hasAnyText(attrSkuId0)) {
            query.eq("msku_attr_sku_00", attrSkuId0);
        }
        if (XStr.hasAnyText(attrSkuId1)) {
            query.eq("msku_attr_sku_01", attrSkuId1);
        }
        if (XStr.hasAnyText(attrSkuId2)) {
            query.eq("msku_attr_sku_02", attrSkuId2);
        }


        return SvcM2Sku.getApp().first(query);
    }

    /**
     * 能否编辑
     *
     * @param skuId
     */
    @SneakyThrows
    public XReturn canEdit(String skuId, Boolean throwEx) {
        M2Sku entitySku = SvcM2Sku.getApp().getEntity(skuId);

        M2Spu entitySpu = SvcM2Spu.getApp().getEntity(entitySku.getMsku_spu_id());
        XReturn r = entitySpu.canEdit();
        if (r.err()) {
            if (throwEx) {
                throw new XException(r);
            }
        }

        return r;
    }

    /**
     * 商品规格限购检查
     *
     * @param skuData sku信息
     * @param wxFrom  用户
     * @param count   购买数量
     */
    public XReturn validLimit(SkuData skuData, String wxFrom, long count) {
        if (count <= 0) {
            return XReturn.getR(20085, "购买数量异常，" + count);
        }
        //限购
        //Long limitMax = skuData.getEntity().limitMax();
        //long skuCount = SvcMallOrder.getBean().getSkuCount(wxFrom, skuData.getEntity().getMsku_id());
        //if (skuCount > limitMax) {
        //    return XReturn.getR(20087, "商品最多购买" + limitMax);
        //}

        if (skuData.getStock_count_left() < count) {
            return XReturn.getR(20087, "商品库存不足," + skuData.getStock_count_left());
        }

        return XReturn.getR(0);
    }

    /**
     * 商品规格是否有效
     *
     * @param skuData
     */
    public XReturn valid(SkuData skuData) {
        if (skuData.getEntity().getMsku_enable() != 1) {
            return XReturn.getR(20075, "商品规格已下架");
        }

        if (skuData.getMspu_enable() != 1) {
            return XReturn.getR(20076, "商品已下架");
        }

        if (skuData.getEntity().getMsku_price().doubleValue() <= 0) {
            return XReturn.getR(20077, "商品价格异常");
        }

        return XReturn.getR(0);
    }


    /**
     * sku 列表
     *
     * @param spuId
     */
    @SneakyThrows
    public List<SkuData> getList(String spuId, List<String> skuId) {
        JoinWrapperPlus<M2Sku> query = listQuery(spuId, skuId);
        //join
        query.join(SysStock.table(), "stock_id_src", "msku_id");
        query.join(M2Spu.table(), "msku_spu_id", "mspu_id");
        //
        String[] select = {
                "t_m2_sku.*"
                , "mspu_enable", "mspu_id", "mspu_name", "mspu_img"
                , "stock_count_left", "stock_count_use"
        };
        query.select(select);
        List<Map<String, Object>> list = SvcM2Sku.getApp().mapper().getMaps(query);//sku
        List<SkuData> listSku = new ArrayList<>();
        for (Map<String, Object> data : list) {
            SkuData skuData = new SkuData();
            XBean.fromMap(data, skuData);

            M2Sku entitySku = SvcM2Sku.getApp().loadEntity(data);
            skuData.setEntity(entitySku);

            listSku.add(skuData);
        }

        return listSku;
    }


    /**
     * 设置上下架
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn setEnable(List<String> ids, Integer enable) {
        canEdit(ids.get(0), true);

        if (enable == 1 || enable == 0) {
            //pass
        } else {
            return EnumSys.ERR_VAL.getR("enable参数异常");
        }
        List<M2Sku> list = SvcM2Sku.getApp().listByIds(ids);
        for (M2Sku entitySku : list) {
            if (enable == 1) {
                if (entitySku.getMsku_price().doubleValue() <= 0) {
                    throw new XException(entitySku.getKey() + ":商品规格金额不能为0");
                }
            }
        }

        //设置上下架
        SvcM2Sku.getApp().update().set("msku_enable", enable)
                .in("msku_id", ids)
                .update();

        return XReturn.getR(0);
    }


    /**
     * 设置库存
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn setStock(List<SkuSetStockVo> listVo) {
        canEdit(listVo.get(0).getSku_id(), true);

        XReturn r = XReturn.getR(0);
        SysStockService app = SysStockService.getBean();
        for (SkuSetStockVo vo : listVo) {
            if (XStr.isNullOrEmpty(vo.getSku_id())) {
                throw new XException("miss sku_id");
            }
            SysStock entity = app.updateLeft(vo.getSku_id(), vo.getLeft_count(), vo.getLeft_count_old());
            r.setData(vo.getSku_id(), entity);
        }

        return r;
    }
}
